#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "window.h"
#include "buffer.h"
#include "undo.h"
#include "fileio.h"
#include "list.h"

window_t *current_window;

window_t * window_new(const char *path)
{
    window_t *win = NULL;

    if ((win = (window_t *)malloc(sizeof(window_t))) == NULL) {
	perror("Out of memory!");
	exit(1);
    }
    if ((win->path = (char *)malloc(strlen(path) + 1)) == NULL) {
	perror("Out of memory!");
	exit(1);
    }

    win->buf = NULL;
    win->head_buf = NULL;
    win->tail_buf = NULL;
    win->num_cmds = 1;
    win->multiple = FALSE;
    win->undo_cmd = NULL;
    win->redo_cmd = NULL;
    win->is_saved = TRUE;
    strcpy(win->path, path);
    INIT_LIST_HEAD(&(win->list));

    return win;
}

void window_create_window(const char *path) {
    if (current_window == NULL) { /* The first time */
	current_window = window_new(path);
    } else {
	window_t *win = window_new(path);
	window_t *old_win = current_window;
	list_add(&(win->list), &(old_win->list));
	current_window = win;
    }
}

void window_remove_window(window_t *win)
{
    window_t *next_win = window_next(win);
    if (next_win != win) {
	list_del(&(win->list));
	current_window = next_win;
    } else {
	current_window = NULL;
    }
    window_free(win);
}

void window_free(window_t *win)
{
    buf_clear_bufs(win->buf);
    undo_cmd_clear_cmds(win->undo_cmd);
    undo_cmd_clear_cmds(win->redo_cmd);
    free(win);
}

window_t * window_next(window_t *win)
{
    if (win == NULL)
	win = current_window;

    return list_entry(win->list.next, window_t, list);

}

window_t * window_prev(window_t *win)
{
    if (win == NULL)
	win = current_window;

    return list_entry(win->list.prev, window_t, list);
}

void window_current_next(void)
{
    current_window = window_next(current_window);
}

void window_current_prev(void)
{
    current_window = window_prev(current_window);
}

